﻿using System.Collections.Generic;
using Ah.Testudin.Engine.Actors;
using Ah.Testudin.Engine.Actors.Components;
using Ah.Testudin.Engine.Events;
using Microsoft.Xna.Framework;

namespace Ah.Testudin.Engine.Processes
{
    public class ActorOutOfBoundsProcess : ProcessBase
    {
        #region Private Member Variables

        private const int DEATH_ZONE_THRESHOLD = -10;

        private const int MAX_FRAME_COUNT = 10;

        private readonly GetAllActorsDelegate _getAllActorsDelegate;

        private readonly IEventManager _eventManager;

        private int _currentFrameCount;

        #endregion

        #region Constructors

        public ActorOutOfBoundsProcess(
            GetAllActorsDelegate getAllActorsDelegate,
            IEventManager eventManager)
        {
            _getAllActorsDelegate = getAllActorsDelegate;

            _eventManager = eventManager;

            _currentFrameCount = 0;
        }

        #endregion

        #region ProcessBase

        public override void Update(GameTime gameTime)
        {
            _currentFrameCount++;

            if (_currentFrameCount >= MAX_FRAME_COUNT)
            {
                _currentFrameCount = 0;

                foreach (Actor currentActor in _getAllActorsDelegate())
                {
                    TransformComponent currentTransformComponent = currentActor.GetComponent<TransformComponent>();

                    if (currentTransformComponent != null)
                    {
                        if (currentTransformComponent.Transform.Translation.Y < DEATH_ZONE_THRESHOLD)
                        {
                            _eventManager.QueueEvent(
                                new ActorDestroyedEvent(
                                    currentActor.Id));
                        }
                    }
                }
            }
        }

        #endregion
    }
}
